// 弹幕系统服务端
let WebSocket = require('ws')
let redis = require('redis')

let redisClient = redis.createClient({
  host: '39.105.27.58',
  port: 6379,
  password: 'lovehxp521..'
})// kay,value

// 创建实例对象
let wss = new WebSocket.Server({port: 3000})
// 存放客户连接
let clientArr = []
// 创建webSocket连接，原生的webSockdt就两个常用方法 on('message') send()
wss.on('connection',function(ws){
  clientArr.push(ws);
  // 当客户刚开始连接就把所有的数据发送给客户
  redisClient.lrange('barrages',0,-1,function (error,applies) {
    applies = applies.map(item => JSON.parse(item))
    ws.send(
      JSON.stringify({ type: 'INIT', data:applies})
    )
  })
  ws.on('message',function (data) {
    //{value:,timem,color}
    redisClient.rpush('barrages',data,redis.print);
    clientArr.forEach(w => {
      w.send(
        JSON.stringify({ type: 'ADD',data: JSON.parse(data)})
      )
    })
  })
  
  // 关闭连接
  ws.on('close',function () {
    // 管滤掉退出的用户
    clientArr = clientArr.filter(client => client!=ws)
  })
})